package com.sx.zongzhi.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.AppealAdapter;
import com.sx.zongzhi.adapter.DealWayAdapter;
import com.sx.zongzhi.adapter.TextSelectAdapter;
import com.sx.zongzhi.bean.AppealBean;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.OrganizingBean;
import com.sx.zongzhi.presenter.AppealPest;
import com.sx.zongzhi.utils.AppConstants;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.Global;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.IAppealView;
import com.sx.zongzhi.widget.LoadDialog;
import com.sx.zongzhi.widget.MyPopupWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * 诉求服务
 */
public class AppealActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener
        ,IAppealView{

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private AppealPest appealPest;
    //诉求状态码:提交需获取的列表对应的数字到后台以获取对应列表数据,对应关系:(50-待办列表,69-已办列表,70-已办结,90-历史遗留列表)
    private AppealAdapter appealAdapter;
    private final SparseArray<String> appealStateCode=new SparseArray<>();
    private List<AppealBean.RowsBean> rowsBeans=new ArrayList<>();
    private List<String> titleTy=new ArrayList<>();
    private MyPopupWindow typePopupWindow,dealPopupWindow;
    private TextSelectAdapter selectAdapter;
    private Disposable disposable;
    /**
     * 当前列表 0：待办 1：已办 2：办结
     */
    private int DEAL_TYPE;
    /**筛选条件*/
    private String orgId="";
    private int currentPage=1;
    private String eventName="";
    private String startTime="";
    private String endTime="";
    private String place="";
    private String eventSource="";
    private String eventTypeId="";
    /**当前的选择的*/
    private AppealBean.RowsBean rowsBean;
    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.refresh_recyclerview);
        ButterKnife.bind(this);
        DEAL_TYPE=getIntent().getIntExtra("DEAL_TYPE",0);
        setTitleName("诉求待处理",R.mipmap.icon_drop_down);
        setRightImage(R.mipmap.icon_nav_search);
        setRightImage2(R.mipmap.icon_nav_position);
        appealPest=new AppealPest(this);
        initView();
        initData();
        onRefresh();
    }

    private void initData() {
        appealStateCode.put(0,"50");//待办
        appealStateCode.put(1,"69");//已办
        appealStateCode.put(2,"70");//办结
        appealStateCode.put(3,"90");//历史遗留
        //订阅筛选组织机构
        disposable= MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent bean) throws Exception {
                        if ("AppealActivity".equals(bean.getRequest())) {
                            if (bean.getType()==0) {
                                OrganizingBean oBean = (OrganizingBean) bean.getMsg();
                                if (oBean != null) {
                                    currentPage = 1;
                                    orgId = oBean.getId();
                                    getDataList();
                                }
                            }else {
                                onRefresh();
                            }
                        }
                    }
                });
    }

    private void initView() {
        switch (DEAL_TYPE){
            case 0:
                setTitleName("诉求待处理");
                setRightImage2Hide();
                break;
            case 1:
                setTitleName("诉求已处理");
                setRightImage2Hide();
                break;
            case 2:
                setTitleName("诉求已办结");
                setRightImage2Show();
                break;
        }

        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeResources(AppConstants.colors);
            swipeRefreshLayout.setOnRefreshListener(this);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        appealAdapter = new AppealAdapter(this,R.layout.item_dispute_pending_list,rowsBeans);
        appealAdapter.setEmptyView(View.inflate(this,R.layout.load_error_view,null));
        recyclerView.setAdapter(appealAdapter);
        appealAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                currentPage++;
                getDataList();
            }
        },recyclerView);
        appealAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(AppealActivity.this, AppealDetailActivity.class)
                        .putExtra("AppealBean.RowsBean",rowsBeans.get(position)));
            }
        });
    }

    /**
     * 事件受理
     * @param appealId 诉求事件id
     *  @param stepRecordId 事件步骤id
     */
    public void acceptDispute(String appealId,String stepRecordId,String type,String content){
        appealPest.acceptAppeal(appealId,stepRecordId,type,content);
    }


    @OnClick({R.id.tv_title,R.id.imv_Right, R.id.imv_Right2})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.tv_title:
                createTypePop();
                break;
            case R.id.imv_Right:
                startActivityForResult(new Intent(AppealActivity.this,AppealSearchActivity.class)
                        ,5551);
                break;
            case R.id.imv_Right2:
                startActivity(new Intent(this,OrganizingActivity.class).
                        putExtra(Global.ACTIVITY_FRAGMENT,"AppealActivity"));
                break;
        }
    }


    @Override
    protected void onDestroy() {
        if (disposable!=null){
            disposable.dispose();
        }
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 5551://查询返回
                    currentPage=1;
                    eventName = intent.getStringExtra("EventName");
                    place = intent.getStringExtra("Location");
                    eventSource = intent.getStringExtra("EventSource");
                    startTime = intent.getStringExtra("StartTime");
                    endTime = intent.getStringExtra("EndTime");
                    eventTypeId = intent.getStringExtra("EventType");
                    getDataList();
                    break;
            }
        }
    }

    /**
     * 创建显示事件类型的弹窗
     */
    private void createTypePop() {
        if (typePopupWindow == null) {
            titleTy.add("诉求待处理");
            titleTy.add("诉求已处理");
            titleTy.add("诉求已办结");
            titleTy.add("历史遗留");
            View view = LayoutInflater.from(this).inflate(R.layout.pop_select_type, null);
            typePopupWindow = new MyPopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            typePopupWindow.setTouchable(true);
            typePopupWindow.setOutsideTouchable(false);
            typePopupWindow.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));
            selectAdapter=new TextSelectAdapter(this,R.layout.item_pop_text_select,titleTy);
            selectAdapter.setItemSelect(DEAL_TYPE);
            ListView listview = (ListView) view.findViewById(R.id.list_View);
            listview.setAdapter(selectAdapter);
            listview.setOnItemClickListener(typeItemClick);
        }

        typePopupWindow.showAsDropDown(findViewById(R.id.toolbar));
    }

    AdapterView.OnItemClickListener typeItemClick=new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            setTitleName(titleTy.get(position));
            if (position>1){
                setRightImage2Show();
            }else {
                setRightImage2Hide();
            }
            selectAdapter.setItemSelect(position);
            typePopupWindow.dismiss();
            DEAL_TYPE=position;
            currentPage=1;
            getDataList();
        }
    };

    private class MyOnItemClickListener implements AdapterView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String dealType= parent.getAdapter().getItem(position).toString();
            if (dealType.equals("加急")){
                createEdit("加急");
            }
            if (dealType.equals("领导批示")){
                createEdit("领导批示");
            }
            if (dealType.equals("普通督办")){
                createEdit("普通督办");
            }
            if (dealType.equals("黄牌督办")){
                createEdit("黄牌督办");
            }
            if (dealType.equals("红牌督办")){
                createEdit("红牌督办");
            }
            dealPopupWindow.dismiss();
        }
    }

    /**
     * 带输入框的dialog
     */
    private void createEdit(final String title) {
        View view=LayoutInflater.from(this).inflate(R.layout.dialog_edittext,null);
        TextView tvTitle= (TextView) view.findViewById(R.id.dialog_title);
        tvTitle.setText(title);
        final EditText etContent= (EditText) view.findViewById(R.id.dialog_message);
        Button btCancel=(Button) view.findViewById(R.id.dialog_back);
        Button btOk=(Button) view.findViewById(R.id.dialog_confirm);
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.setView(view).setCancelable(false).create();
        dialog.show();
        btCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content=etContent.getText().toString();
                if (BaseUtil.isEmpty(content)){
                    ToastUtils.showToast(AppealActivity.this,"请输入您的意见");
                    return;
                }
                if (title.equals("加急")){
                    acceptDispute(rowsBean.getAppealId(),rowsBean.getStepRecordId(),"3010",content);
                }
                if (title.equals("领导批示")){
                    acceptDispute(rowsBean.getAppealId(),rowsBean.getStepRecordId(),"3030",content);
                }
                if (title.equals("普通督办")){
                    acceptDispute(rowsBean.getAppealId(),rowsBean.getStepRecordId(),"1010",content);
                }
                if (title.equals("黄牌督办")){
                    acceptDispute(rowsBean.getAppealId(),rowsBean.getStepRecordId(),"1030",content);
                }
                if (title.equals("红牌督办")){
                    acceptDispute(rowsBean.getAppealId(),rowsBean.getStepRecordId(),"1050",content);
                }
                dialog.dismiss();
            }
        });
    }


    @Override
    public void onRefresh() {
        currentPage=1;
        eventName="";
        startTime="";
        endTime="";
        place="";
        eventSource="";
        eventTypeId="";
        orgId="";
        getDataList();
    }

    public void getDataList() {
        appealPest.getAppealList(appealStateCode.get(DEAL_TYPE),eventName,startTime,endTime,place
                ,eventSource,eventTypeId,orgId,currentPage,6);
    }

    @Override
    public void showError(String message) {
        swipeRefreshLayout.setRefreshing(false);
        ToastUtils.showToast(this,message);
        LoadDialog.dismiss(this);
    }

    @Override
    public void getAppealList(AppealBean appealBean) {
        swipeRefreshLayout.setRefreshing(false);
        if (appealBean.getPermission()!=null){
            if(dealPopupWindow==null){
                createDealPop(appealBean.getPermissionList());
            }
        }

        if (currentPage==1){
            rowsBeans.clear();
            appealAdapter.setNewData(rowsBeans);
        }
        if (appealBean.getRows()!=null) {
            rowsBeans.addAll(appealBean.getRows());
        }
 
        if (rowsBeans.size()>=appealBean.getRecords()){
            appealAdapter.loadMoreEnd();
        }else {
            appealAdapter.loadMoreComplete();
        }
        appealAdapter.notifyDataSetChanged();
    }
    /**
     * 创建更多事件处理的弹窗
     */
    private void createDealPop(List<String> permissionList) {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_select_type, null);
        dealPopupWindow = new MyPopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        dealPopupWindow.setTouchable(true);
        dealPopupWindow.setOutsideTouchable(true);
        dealPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));
        DealWayAdapter dealWayAdapter=new DealWayAdapter(this,R.layout.item_text,permissionList);
        ListView listview = (ListView) view.findViewById(R.id.list_View);
        listview.setAdapter(dealWayAdapter);
        listview.setOnItemClickListener(new MyOnItemClickListener());
        view.findViewById(R.id.fl_Prent).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dealPopupWindow.dismiss();
            }
        });
    }
    /**
     * 显示
     */
    public void showDealPop(AppealBean.RowsBean rowsBean) {
        this.rowsBean=rowsBean;
        if (dealPopupWindow!=null){
            dealPopupWindow.showAsDropDown(findViewById(R.id.toolbar));
        }
    }

    @Override
    public void accept(String str) {
        ToastUtils.showToast(this,str);
        onRefresh();
    }
}
